#include "RelayCP.hpp"

using namespace BFT::order::messages;

RelayCP::RelayCP(boost::shared_ptr<BFT::order::statemanagement::CheckPointState> _cps, uint32_t _sendingReplica)
	: MacMessage::MacMessage(RELAY_CP, computeSize(_cps), _sendingReplica)
{
	checkPoint = _cps;
	
	int offset = getOffset();
	
	int bytes_size;
	boost::shared_ptr<char> bytes = getBytes(bytes_size);
	
	int cp_size;
	boost::shared_ptr<char> cp_bytes = checkPoint.get()->getBytes(cp_size);
	
	//write the checkpoint
	memcpy( (void*)(bytes.get()+offset) , (const void *)(cp_bytes.get()) , cp_size);
	offset += cp_size;
}

RelayCP::RelayCP(boost::shared_ptr<char> _bytes, int _bytes_size)
	: MacMessage::MacMessage(_bytes, _bytes_size)
{
	int offset = getOffset();
	
	//read the checkpoint bytes
	int cp_size = _bytes_size - offset - getAuthenticationSize();
	boost::shared_ptr<char> cp_bytes ( (char*)malloc(cp_size),free );
	memcpy( (void*)(cp_bytes.get()) , (const void*)(_bytes.get()+offset) , cp_size);
	checkPoint.reset(new BFT::order::statemanagement::CheckPointState(cp_bytes, cp_size));
	
	//w.r.t. java implementation, skipping a size check that cannot fail
}

uint32_t RelayCP::computeSize(boost::shared_ptr<BFT::order::statemanagement::CheckPointState> _cps)
{
	return _cps.get()->getSize();
}
